const mongoose = require('mongoose')
const Movie = mongoose.model('Movie')
const Category = mongoose.model('Category')
const Comment = mongoose.model('Comment')
const _ = require('lodash')
const { resolve } = require('path')

// detail page
exports.detail = async (ctx, next) => {
  const id = ctx.params.id

  await Movie.update({_id: id}, {$inc: {pv: 1}})

  const movie = await Movie.findOne({_id: id})
  const comments = await Comment
    .find({movie: id})
    .populate('from', 'name')
    .populate('reply.from reply.to', 'name')

  await ctx.render('pages/detail', {
    title: 'imooc 详情页',
    movie: movie,
    comments: comments
  })
}

// admin new page
exports.new = async (ctx, next) => {
  const categories = await Category.find({})

  await ctx.render('pages/admin', {
    title: 'imooc 后台录入页',
    categories: categories,
    movie: {}
  })
}

// admin update page
exports.update = async (ctx, next) => {
  const id = ctx.params.id

  if (id) {
    const movie = await Movie.findOne({ _id: id })
    const categories = await Category.find({})

    await ctx.render('pages/admin', {
      title: 'imooc 后台更新页',
      movie: movie,
      categories: categories
    })
  }
}

const util = require('../../libs/util')

// admin poster
exports.savePoster = async (ctx, next) => {
  const posterData = ctx.request.body.files.uploadPoster
  const filePath = posterData.path
  const name = posterData.name

  if (name) {
    const data = await util.readFileAsync(filePath)
    const timestamp = Date.now()
    const type = posterData.type.split('/')[1]
    const poster = timestamp + '.' + type
    const newPath = resolve(__dirname, '../../../../', 'public/upload/' + poster)

    await util.writeFileAsync(newPath, data)

    ctx.poster = poster
  }

  await next()
}

// admin post movie
exports.save = async (ctx, next) => {
  let movieObj = ctx.request.body.fields || {}
  let _movie

  if (ctx.poster) {
    movieObj.poster = ctx.poster
  }

  if (movieObj._id) {
    let movie = await Movie.findOne({ _id: movieObj._id })

    _movie = _.extend(movie, movieObj)
    await _movie.save()

    ctx.redirect('/movie/' + movie._id)
  } else {
    _movie = new Movie(movieObj)

    const categoryId = movieObj.category
    const categoryName = movieObj.categoryName

    await _movie.save()

    if (categoryId) {
      let category = await Category.findOne({ _id: categoryId })

      category.movies.push(_movie._id)
      await category.save()

      ctx.redirect('/movie/' + _movie._id)
    } else if (categoryName) {
      let category = new Category({
        name: categoryName,
        movies: [_movie._id]
      })

      await category.save()
      _movie.category = category._id
      await _movie.save()

      ctx.redirect('/movie/' + _movie._id)
    }
  }
}

// list page
exports.list = async (ctx, next) => {
  const movies = await Movie.find({})
    .populate('category', 'name')

  await ctx.render('pages/list', {
    title: 'imooc 列表页',
    movies: movies
  })
}

// list page
exports.del = async (ctx, next) => {
  const id = ctx.query.id

  if (id) {
    try {
      await Movie.remove({ _id: id })

      ctx.body = { success: 1 }
    } catch (err) {
      ctx.body = { success: 0 }
    }
  }
}
